"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 功能
Case Name   : 主实例节点网络故障
Create At   : 2023/05/18
Owner       : opentestcase043
Description :
        测试点：闪断
        1.查询注入故障前集群状态
        2.主节点注入网络链路闪断故障
        3.查看集群状态
        4.网络恢复后查看集群状态
        测试点：延时
        5.查询注入故障前集群状态
        6.主节点注入网络包延迟故障
        7.查看集群状态
        8.网络恢复后查看集群状态
        测试点：停止网卡
        9.查询注入故障前集群状态
        10.主节点注入停止网卡故障
        11.查看集群状态
        12.网络恢复后查看集群状态
        13.清理环境
Expect      :
        1.集群状态正常
        2.注入故障成功
        3.集群状态异常
        4.状态正常
        5.集群状态正常
        6.注入故障成功
        7.集群状态异常
        8.集群状态正常
        9.集群状态正常
        10.注入故障成功
        11.集群状态断网无法输入命令
        12.集群状态正常
        13.清理环境成功
History     :
"""

import os
import unittest
import time

from testcase.utils.ComThread import ComThread
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from yat.test import Node

LOG = Logger()
Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == Primary_SH.get_node_num(), '单机环境不执行')
class ShareStorage(unittest.TestCase):

    def setUp(self):
        LOG.info('-----this is setup-----')
        LOG.info(f'-----{os.path.basename(__file__)} start-----')
        self.con = Constant()
        self.com = Common()
        self.pri_root_node = Node('PrimaryRoot')
        self.pri_node = Node('PrimaryDbUser')
        self.s1_sh = CommonSH('Standby1DbUser')

        LOG.info('----获取网卡----')
        network_card_cmd = 'ifconfig'
        LOG.info(network_card_cmd)
        network_card_result = self.pri_root_node.sh(
            network_card_cmd).result()
        network_card_list = network_card_result.split('\n\n')
        LOG.info(network_card_list)
        self.networkcard = ''
        for network_card_item in network_card_list:
            if self.pri_node.db_host in network_card_item:
                self.networkcard = network_card_item.split(':')[0].strip()
                LOG.info(self.networkcard)
                break

    def test_share_storage(self):
        text = '-----step1:查询注入故障前集群状态; expect:集群状态正常-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)
        res = status.splitlines()[-1].split('|')[0].split('6001')[1]
        self.assertIn('P Primary Normal', res, '执行失败:' + text)

        text = '-----step2:主节点注入网络链路闪断故障; expect:注入故障成功-----'
        LOG.info(text)
        begin_time = time.time()
        inject_command = f" rNetLink_flash (repeat,duration,interval,dev) " \
                         f"values (10,5,2,{self.networkcard})"
        cfe_thread = ComThread(
            self.com.execute_cfe,
            args=(self.pri_root_node, "inject", inject_command))
        cfe_thread.setDaemon(True)
        cfe_thread.start()
        cfe_thread.join()

        text = '-----step3:查看集群状态; expect:集群状态异常-----'
        LOG.info(text)
        time.sleep(10)
        while time.time() - begin_time <= 65:
            status = self.s1_sh.exec_cm_ctl('query', '-Cv')
            LOG.info(status)
            self.assertNotIn('cluster_state   : Normal', status,
                             '执行失败:' + text)
            time.sleep(10)

        text = '-----step4:网络恢复后查看集群状态; expect:状态正常-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('stop')
        self.assertIn(self.con.cm_stop_success_msg, status,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('start')
        self.assertIn(self.con.cm_start_success_msg, status,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('switchover', '-a')
        LOG.info(status)
        self.assertIn(self.con.cm_switchover_success_msg, status,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)
        res = status.splitlines()[-1].split('|')[0].split('6001')[1]
        self.assertIn('P Primary Normal', res, '执行失败:' + text)

        text = '-----step5:查询注入故障前集群状态; expect:集群状态正常-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)
        res = status.splitlines()[-1].split('|')[0].split('6001')[1]
        self.assertIn('P Primary Normal', res, '执行失败:' + text)

        text = '-----step6:主节点注入网络包延迟故障; expect:注入故障成功-----'
        LOG.info(text)
        begin_time = time.time()
        inject_command = f"rNet_delay_Ex (dev, time, duration) " \
                         f"values({self.networkcard}, 3000ms, 50)"
        cfe_thread = ComThread(
            self.com.execute_cfe,
            args=(self.pri_root_node, "inject", inject_command))
        cfe_thread.setDaemon(True)
        cfe_thread.start()
        cfe_thread.join()
        time.sleep(10)
        query_command = f" rNet_delay where dev={self.networkcard}"
        result = self.com.execute_cfe(self.pri_root_node, "query",
                                      query_command)
        LOG.info(result)
        self.assertIn("3.0s", result, '执行失败:' + text)

        text = '-----step7:查看集群状态; expect:集群状态异常-----'
        LOG.info(text)
        while time.time() - begin_time <= 50:
            status = self.s1_sh.exec_cm_ctl('query', '-Cv')
            LOG.info(status)
            self.assertNotIn('cluster_state   : Normal', status,
                             '执行失败:' + text)
            time.sleep(5)

        text = '-----step8:网络恢复后查看集群状态; expect:集群状态异常-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('stop')
        self.assertIn(self.con.cm_stop_success_msg, status,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('start')
        self.assertIn(self.con.cm_start_success_msg, status,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('switchover', '-a')
        LOG.info(status)
        self.assertIn(self.con.cm_switchover_success_msg, status,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)
        res = status.splitlines()[-1].split('|')[0].split('6001')[1]
        self.assertIn('P Primary Normal', res, '执行失败:' + text)

        text = '-----step9:查询注入故障前集群状态; expect:集群状态正常-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)
        res = status.splitlines()[-1].split('|')[0].split('6001')[1]
        self.assertIn('P Primary Normal', res, '执行失败:' + text)

        text = '-----step10:主节点注入停止网卡故障; expect:注入故障成功-----'
        LOG.info(text)
        begin_time = time.time()
        inject_command = f"rNet_down (dev, time) " \
                         f"values({self.networkcard}, 30)"
        cfe_thread = ComThread(
            self.com.execute_cfe,
            args=(self.pri_root_node, "inject", inject_command))
        cfe_thread.setDaemon(True)
        cfe_thread.start()
        cfe_thread.join()
        time.sleep(5)

        text = '-----step11:查看集群状态; expect:集群状态异常-----'
        LOG.info(text)
        while time.time() - begin_time <= 30:
            status = self.s1_sh.exec_cm_ctl('query', '-Cv')
            LOG.info(status)
            self.assertNotIn('cluster_state   : Normal', status,
                             '执行失败:' + text)
            time.sleep(5)

        text = '-----step12:网络恢复后查看集群状态; expect:重启成功，状态正常-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('stop')
        self.assertIn(self.con.cm_stop_success_msg, status,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('start')
        self.assertIn(self.con.cm_start_success_msg, status,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('switchover', '-a')
        LOG.info(status)
        self.assertIn(self.con.cm_switchover_success_msg, status,
                      '执行失败:' + text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)
        res = status.splitlines()[-1].split('|')[0].split('6001')[1]
        self.assertIn('P Primary Normal', res, '执行失败:' + text)

    def tearDown(self):
        text = '-----this is tearDown-----'
        LOG.info(text)
        text = '-----step13:清理环境; expect:清理环境成功-----'
        LOG.info(text)
        status1 = Primary_SH.exec_cm_ctl('stop')
        status2 = Primary_SH.exec_cm_ctl('start')
        status3 = Primary_SH.exec_cm_ctl('switchover', '-a')
        status4 = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status1)
        LOG.info(status2)
        LOG.info(status3)
        LOG.info(status4)
        self.assertIn(self.con.cm_stop_success_msg, status1,
                      '执行失败:' + text)
        self.assertIn(self.con.cm_start_success_msg, status2,
                      '执行失败:' + text)
        self.assertIn(self.con.cm_switchover_success_msg, status3,
                      '执行失败:' + text)
        self.assertIn('cluster_state   : Normal', status4, '执行失败:' + text)
        res = status4.splitlines()[-1].split('|')[0].split('6001')[-1]
        self.assertIn('P Primary Normal', res, '执行失败:' + text)
        LOG.info(f'-----{os.path.basename(__file__)} end-----')
